

<template>
  <view class="Mall4j container">
    <!-- 头部菜单 -->
    <view class="order-tit">
      <text data-sts="0" :class="sts==0?'on':''" @tap="onStsTap">{{ i18n.all }}</text>
      <text data-sts="1" :class="sts==1?'on':''" @tap="onStsTap">{{ i18n.toBePaid }}</text>
      <text data-sts="2" :class="sts==2?'on':''" @tap="onStsTap">{{ i18n.toBeDelivered }}</text>
      <text data-sts="3" :class="sts==3?'on':''" @tap="onStsTap">{{ i18n.toBeReceived }}</text>
      <text data-sts="5" :class="sts==5?'on':''" @tap="onStsTap">{{ i18n.completed }}</text>
    </view>
    <!-- 头部菜单 end -->

    <view class="main">
      <!-- 订单列表 -->
      <block v-for="(item, index) in list" :key="index">
        <view class="prod-item">
          <view class="order-num">
            <text>{{ i18n.orderNumber }}：{{ item.orderNumber }}</text>
            <view class="order-state">
              <text :class="'order-sts  ' + (item.status==1?'red':'') + '  ' + ((item.status==5||item.status==6)?'gray':'')">{{ ['',i18n.toBePaid,i18n.toBeDelivered,i18n.toBeReceived,i18n.toBeEvaluated,i18n.completed,i18n.cancelled,i18n.inAGroup][item.status] }}</text>
              <!-- 退款状态 -->
              <view class="red">
                <!-- returnMoneySts 退款状态 1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请(无) 7.商家拒绝(无) -1.退款关闭 -->
                <!-- refundStatus 订单退款状态参考（1:申请退款 2:退款成功 3:部分退款成功 4:退款失败 -->
                <text v-if="item.returnMoneySts==0" />
                <text v-if="item.returnMoneySts==1||item.returnMoneySts==2||item.returnMoneySts==3||item.returnMoneySts==4">({{ i18n.refunding }}
                  <block v-if="item.status <= 2 && item.deliveryCount && item.productNums > item.deliveryCount">, {{ i18n.partialDelivery }}</block>)
                </text>
                <!-- 部分退款关闭（退款中）item.refundStatus === 1 && item.returnMoneySts === -1 -->
                <text v-if="item.refundStatus === 1 && item.returnMoneySts === -1">({{ i18n.refunding }}
                  <block v-if="item.status <= 2 && item.deliveryCount && item.productNums > item.deliveryCount">, {{ i18n.partialDelivery }}</block>)
                </text>
                <!-- <text v-if="item.returnMoneySts==5||item.returnMoneySts==7">({{i18n.refundComplete}})</text> -->
                <!-- 退款完成 -->
                <text v-if="item.returnMoneySts == 5 && item.refundStatus !== 3">({{ i18n.refundComplete }})</text>
                <!-- 部分退款完成refundStatus === 3 && returnMoneySts === 5 -->
                <text v-if="item.returnMoneySts == 5 && item.refundStatus == 3 && (item.status > 2 || (item.status === 2 && !item.deliveryCount))">
                  ({{ i18n.partialRefundCompleted }})
                </text>
                <!-- 部分发货, 部分退款 -->
                <text v-if="item.status <= 2 && item.deliveryCount && item.productNums > item.deliveryCount && item.returnMoneySts == 5 && item.refundStatus == 3">
                  ({{ i18n.partialRefund }}, {{ i18n.partialDelivery }})
                </text>
                <!-- 部分发货 -->
                <text v-if="!item.refundStatus && item.status <= 2 && item.deliveryCount && item.productNums > item.deliveryCount">
                  ({{ i18n.partialDelivery }})
                </text>
                <!-- 退款关闭 -->
                <text v-if="item.refundStatus !== 1 && item.returnMoneySts==-1 && (item.status > 2 || (item.status === 2 && !item.deliveryCount))">
                  ({{ i18n.refundClosed }})
                </text>
                <!-- 退款关闭, 部分发货 -->
                <text v-if="item.refundStatus !== 1 && item.returnMoneySts==-1 && item.status <= 2 && item.deliveryCount && item.productNums > item.deliveryCount">
                  ({{ i18n.refundClosed }}, {{ i18n.partialDelivery }})
                </text>
              </view>
              <!-- 删除订单按钮 -->
              <view v-if="(item.status==5 || item.status==6) && (item.returnMoneySts>4 || item.returnMoneySts==-1 || item.returnMoneySts==null || item.returnMoneySts=='')" class="clear-btn">
                <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/clear-his.png" class="clear-list-btn" :data-ordernum="item.orderNumber" @tap="delOrderList" />
              </view>
            </view>
          </view>

          <!-- 商品列表 -->
          <!-- 一个订单单个商品的显示 -->
          <block v-if="item.orderItemDtos.length==1">
            <block v-for="(prod, orderNumber) in item.orderItemDtos" :key="orderNumber">
              <view>
                <view class="item-cont" :data-ordernum="item.orderNumber" @tap="toOrderDetailPage">
                  <view class="prod-pic">
                    <image v-if="prod.pic" :src="prod.pic" />
                    <image v-else src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/def.png" mode="aspectFit" />
                  </view>
                  <view class="prod-info">
                    <view class="prodname">{{ prod.prodName }}</view>
                    <view class="sku-box">
                      <!-- 拼团icon -->
                      <view v-if="item.orderType" class="spell-group-icon">
                        <!-- orderType 订单类型(0普通订单 1团购订单 2秒杀订单) -->
                        {{ ['',i18n.aGroup,i18n.spike,i18n.integral][item.orderType] }}
                      </view>
                      <!-- /拼团icon -->
                      <!-- 配送类型 1:快递 2:自提 3：无需快递) -->
                      <text v-if="item.dvyType == 2" class="spell-group-icon">{{ i18n.pickitUp }}</text>
                      <view class="prod-info-cont">{{ prod.skuName || '' }}</view>
                    </view>
                    <view class="price-nums">
                      <text class="prodprice">
                        <text v-if="prod.price" class="symbol">￥</text>
                        <text v-if="prod.price" class="big-num">{{ wxs.parsePrice(prod.price)[0] }}</text>
                        <text v-if="prod.price" class="small-num">.{{ wxs.parsePrice(prod.price)[1] }}</text>
                      </text>
                      <text class="prodcount">x{{ prod.prodCount }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </block>
          </block>
          <!-- 一个订单多个商品时的显示 -->
          <block v-else>
            <view class="item-cont" :data-ordernum="item.orderNumber" @tap="toOrderDetailPage">
              <scroll-view scroll-x="true" scroll-left="0" scroll-with-animation="false" class="categories">
                <block v-for="(prod, prodId) in item.orderItemDtos" :key="prodId">
                  <view class="prod-pic">
                    <!-- 拼团icon -->
                    <!-- <view class="spell-group-order"><image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/spell-group-order.png"></image></view> -->
                    <!-- 拼团icon -->
                    <image v-if="prod.pic" :src="prod.pic" />
                    <image v-else src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/def.png" mode="aspectFit" />
                  </view>
                </block>
              </scroll-view>
            </view>
          </block>

          <view class="total-num">
            <text class="prodcount">{{ i18n.inTotal }}{{ item.totalCounts }}{{ i18n.items }}</text>
            <view class="prodprice">{{ i18n.totalAmount }}：<text v-if="item.actualTotal" class="symbol">￥</text>
              <text v-if="item.actualTotal" class="big-num">{{ wxs.parsePrice(item.actualTotal)[0] }}</text>
              <text v-if="item.actualTotal" class="small-num">.{{ wxs.parsePrice(item.actualTotal)[1] }}</text>
              <text v-if="item.actualTotal && item.userScore" class="small-num" decode="true">&ensp;+&ensp;</text>
              <text v-if="item.userScore" class="big-num">{{ item.userScore }} {{ i18n.integral }}</text>
            </view>
          </view>
          <!-- end 商品列表 -->
          <view class="prod-foot">
            <view class="btn">
              <view v-if="((item.orderInvoiceId && item.status !== 6) ||
                  (item.orderInvoiceId && (item.status === 6 && item.refundStatus))) && item.status !== 1 && item.orderType !== 3" class="button" @tap="viewIinvoice(item.orderNumber,item.orderInvoiceId)">{{ i18n.invoice.viewInvoice }}</view>
              <view v-if="!item.orderInvoiceId &&item.status !== 6 && item.status !== 1 && item.orderType !== 3" class="button" @tap="showInvoicePopup(item.shopId ,item.orderNumber)">{{ i18n.invoice.InvoicingRequest }}</view>
              <text v-if="item.status==1" class="button" :data-ordernum="item.orderNumber" hover-class="none" @tap="onCancelOrder">{{ i18n.cancelOrder }}</text>
              <!-- <text class="button warn" bindtap="" data-ordernum="{{item.orderNumber}}" hover-class='none'>再次购买</text> -->
              <text v-if="item.status==1" class="button warn" hover-class="none" @tap="onPayAgain(item.dvyType,item.orderType,item.orderNumber)">{{ i18n.payment }}</text>
              <text v-if="(item.status==3 || item.status==5) && item.dvyType == 1" class="button" :data-ordernum="item.orderNumber" hover-class="none" @tap="toDeliveryPage">{{ i18n.viewLogistics }}</text>
              <text v-if="item.status==3" class="button warn" :data-ordernum="item.orderNumber" hover-class="none" @tap="onConfirmReceive">{{ i18n.confirmRceipt }}</text>
              <!-- 评价status==5 -->
              <text v-if="item.status==5 && !item.orderItemDtos.some(val=>val.commSts !== 0)&& item.orderItemDtos.some(val=>val.returnMoneySts !== 5&&val.commSts === 0)&& item.orderType!==3 && item.refundStatus!==1" class="button warn" :data-info="JSON.stringify(item.orderItemDtos)" :data-ordernum="item.orderNumber" hover-class="none" @tap="onComment(item.orderItemDtos||item)">{{ i18n.evaluation }}</text>
            </view>
          </view>
        </view>
      </block>
      <!-- 订单列表 end -->
    </view>
    <!-- 返回首页的悬浮按钮 -->
    <view class="home" @tap="HomePage()">
      <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/order-home.png" />
    </view>
    <!-- 到底了~ -->
    <view v-if="loadAll && list.length!==0" class="loadall">{{ i18n.endTips }}</view>
    <!-- 空 -->
    <empty v-if="list.length==0" />
    <invoiceEdit v-if="isShowInvoicePopup" :shop-id="invoiceShopId" :order-number="invoiceOrderNumber" @closePopup="closePopup" @getData="getOrderDataList" />
  </view>
</template>

<script module="wxs" lang="wxs" src="../../wxs/number.wxs"></script>
<script>
const http = require("../../utils/http.js")
const config = require("../../utils/config.js")
const util = require("../../utils/util.js")
import { PayType, AppType } from "../../utils/constant.js"
import Pay from "../../utils/pay.js"
import empty from "../../components/empty-tips/index.vue"
import invoiceEdit from '../../components/invoice-edit/index.vue'

export default {
  data () {
    return {
      list: [],
      current: 1,
      size: 10,
      pages: 0,
      sts: 0,
      endTime: '',
      loadAll: false, // 已加载全部
      invoiceShopId: '',
      isShowInvoicePopup: false,
      invoiceOrderNumber: '' // 当前选择发票的id
    }
  },

  components: {
    empty,
    invoiceEdit
  },

  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.sts) {
      this.setData({
        sts: options.sts
      });
    }
  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    // 加载导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.orderList
    });
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    this.loadOrderData(this.sts, 1);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.current < this.pages) {
      this.loadOrderData(this.sts, this.current + 1);
    } else {
      this.setData({
        loadAll: true
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
  methods: {
    // 发票信息弹窗
    showInvoicePopup (shopId, invoiceOrderNumber) {
      this.invoiceShopId = shopId
      this.invoiceOrderNumber = invoiceOrderNumber
      this.isShowInvoicePopup = true
    },
    // 关闭弹窗
    closePopup () {
      this.isShowInvoicePopup = false
    },
    getOrderDataList () {
      this.loadOrderData(this.sts, this.current)
    },
    // 查看发票
    viewIinvoice (orderNumber, orderInvoiceId) {
      uni.navigateTo({
        url: `/pages/invoice-detail/invoice-detail?orderNumber=${orderNumber}&orderInvoiceId=${orderInvoiceId}`
      })
    },
    /**
     * 加载订单数据
     */
    loadOrderData: function (sts, current) {
      var ths = this;

      var params = {
        url: "/p/myOrder/myOrder",
        method: "GET",
        data: {
          current: current,
          size: this.size,
          status: sts
        },
        callBack: function (res) {
          var temp = [];
          res.records.forEach(orderItem => {
            orderItem.totalCounts = 0;
            orderItem.orderItemDtos.forEach(prod => {
              orderItem.totalCounts += prod.prodCount;
            });
          });
          if (res.current == 1) {
            temp = res.records;
          } else {
            temp = ths.list;
            temp = ths.list.concat(res.records)
          }
          ths.list = temp
          ths.pages = res.pages
          ths.current = res.current
        }
      };
      http.request(params);
    },

    /**
     * 状态点击事件
     */
    onStsTap: function (e) {
      util.tapLog(3)
      var sts = e.currentTarget.dataset.sts;
      this.setData({
        sts: sts
      });
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
      this.loadOrderData(sts, 1);
      this.setData({
        loadAll: false
      })
    },

    /**
     * 查看物流
     */
    toDeliveryPage: function (e) {
      util.tapLog(3)
      uni.navigateTo({
        url: '/pages/logistics-info/logistics-info?orderNumber=' + e.currentTarget.dataset.ordernum
      });
    },

    /**
     * 取消订单
     */
    onCancelOrder: function (e) {
      util.tapLog(3)
      var ordernum = e.currentTarget.dataset.ordernum;
      var ths = this;
      uni.showModal({
        title: '',
        content: ths.i18n.cancelOrderTips,
        confirmColor: "#3e62ad",
        cancelColor: "#3e62ad",
        cancelText: ths.i18n.cancel,
        confirmText: ths.i18n.confirm,

        success (res) {
          if (res.confirm) {
            var params = {
              url: "/p/myOrder/cancel/" + ordernum,
              method: "PUT",
              data: {},
              callBack: function (res) {
                ths.loadOrderData(ths.sts, 1);
              }
            };
            http.request(params);
          } else if (res.cancel) {//console.log('用户点击取消')
          }
        }
      });
    },

    /**
     * 付款
     */
    onPayAgain: function (dvyType, orderType, orderNumber) {
      util.tapLog(3)
      var params = {
        url: "/p/order/getOrderPayInfoByOrderNumber",
        method: "GET",
        data: {
          orderNumbers: orderNumber
        },
        callBack: res => {
          this.setData({
            //订单过期时间
            endTime: res.endTime,
          });
          // 在IOS中，new Date中指定的字符串有格式:new Date("2018/04/27 11:11")，这样才能正确返回结果
          var et = this.endTime.replace(/-/g, "/")
          var nowTime = new Date().getTime();//现在时间（时间戳）
          var endTime = new Date(et).getTime();//结束时间（时间戳）
          var time = (endTime - nowTime) / 1000;//距离结束的毫秒数
          if (time > 0) {
            uni.navigateTo({
              url: `/pages/pay-way/pay-way?orderNumbers=${orderNumber}&dvyType=${dvyType}&orderType=${orderType}`
            })
          } else {
            uni.showModal({
              title: this.i18n.tips,
              content: this.i18n.orderExpired,
              cancelText: this.i18n.cancel,
              confirmText: this.i18n.confirm,
              showCancel: false,
              confirmColor: "#FF6D13",
              success: (res) => {
                if (res.confirm) {
                  this.loadOrderData(this.sts, 1);
                } else if (res.cancel) {
                  //console.log('用户点击取消')
                }
              }
            });
            return;
          }
        }
      };
      http.request(params);
    },

    /**
     * 查看订单详情
     */
    toOrderDetailPage: function (e) {
      util.tapLog(3)
      // uni.navigateTo({
      //   url: '/pages/order-detail/order-detail?orderNum=' + e.currentTarget.dataset.ordernum
      // });
      this.$Router.push({ path: '/pages/order-detail/order-detail', query: { orderNum: e.currentTarget.dataset.ordernum } })
    },

    /**
     * 确认收货
     */
    onConfirmReceive: function (e) {
      util.tapLog(3)
      var ths = this;
      uni.showModal({
        title: '',
        content: ths.i18n.haveRceivedGoods,
        cancelText: ths.i18n.cancel,
        confirmText: ths.i18n.confirm,
        confirmColor: "#FF6D13",

        success (res) {
          if (res.confirm) {
            var params = {
              url: "/p/myOrder/receipt/" + e.currentTarget.dataset.ordernum,
              method: "PUT",
              data: {},
              callBack: function (res) {
                //console.log(res);
                ths.loadOrderData(ths.sts, 1);
              }
            };
            http.request(params);
          } else if (res.cancel) {//console.log('用户点击取消')
          }
        }

      });
    },
    //删除已完成||已取消的订单
    delOrderList: function (e) {
      util.tapLog(3)
      var ths = this;
      uni.showModal({
        title: '',
        content: ths.i18n.sureDeleteOrder,
        cancelText: ths.i18n.cancel,
        confirmText: ths.i18n.confirm,
        confirmColor: "#FF6D13",

        success (res) {
          if (res.confirm) {
            var ordernum = e.currentTarget.dataset.ordernum;
            var params = {
              url: "/p/myOrder/" + ordernum,
              method: "DELETE",
              data: {},
              callBack: function (res) {
                ths.loadOrderData(ths.sts, 1);
              }
            };
            http.request(params);
          } else if (res.cancel) {
          }
        }

      });
    },

    /**
     * 跳转评价页面
     */
    onComment: function (orderItems) {
      console.log(orderItems)
      // 把商品项缓存起来
      const preCommentData = []
      orderItems.forEach(el => {
        if (el.returnMoneySts !== 5 && el.commSts === 0) {
          preCommentData.push({
            spuName: el.spuName,
            pic: el.pic,
            orderItemId: el.orderItemId,
            shopId: el.shopId,
            skuName: el.skuName
          })
        }
      })
      uni.setStorageSync('orderItemInfo', preCommentData)
      uni.navigateTo({
        url: '/pages/prod-comm/prod-comm'
      })
    },
    /**
     * 跳转首页
     */
    HomePage () {
      this.$Router.pushTab('/pages/index/index')
    }
  }
};
</script>
<style scoped lang='scss'>
@import "./order-list.scss";
</style>
